package com.open.tool;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;

public class ImageSelectorController {
    @FXML private TextField urlField;
    private Stage selectorStage;
    // 添加一个初始化方法，在 FXML 加载后调用
    @FXML
    public void initialize() {
        // 确保 selectorStage 已经被设置
        // 在初始化方法中创建 selectorStage
        selectorStage =SceneCache.ImageSelectorStage;

    }
    @FXML
    private void chooseLocalFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif","*.jpeg","*.bmp")
        );
        File file = fileChooser.showOpenDialog(null);
        if (file != null) {
            openImageViewer(file.toURI().toString());
        }
    }

    @FXML
    private void loadFromUrl() {
        String url = urlField.getText().trim();
        if (!url.isEmpty()) {
            openImageViewer(url);
        }
    }

    private void openImageViewer(String imageUrl) {
        try {
            selectorStage =SceneCache.ImageSelectorStage;

            FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/open/tool/ImageViewer.fxml"));
            Parent root = loader.load();
            ImageViewerController controller = loader.getController();
            controller.loadImage(imageUrl);

            Stage viewerStage = new Stage();
            Scene scene = new Scene(root);
            viewerStage.setTitle("Image Viewer");
            viewerStage.setScene(scene);

            // 在使用 selectorStage 之前进行空检查
            if (selectorStage == null) {
                throw new IllegalStateException("selectorStage is null. Make sure setStage() has been called.");
            }

            // 设置关闭回调
            controller.setOnCloseCallback(() -> {
                selectorStage.show();
                viewerStage.close();
            });
            SceneCache.ImageViewerStage=viewerStage;
            viewerStage.show();

            // 隐藏选择器窗口
            selectorStage.hide();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
